package com.mimosa.common.message;

import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.mimosa.common.system.user.TUser;

public class ThreadSendMail extends Thread {

	private TSiteMessage siteMessage;

	private TUser user;

	private SendSetting sendsetting;

	private final static String HOST = "mail.smtp.host";

	private final static String AUTH = "mail.smtp.auth";

	public ThreadSendMail(TSiteMessage siteMessage, TUser user, SendSetting ss) {
		this.siteMessage = siteMessage;
		this.user = user;
		this.sendsetting = ss;
	}

	@Override
	public void run() {
		try {
			this.send();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发送带有附件的邮件
	 * 
	 * @throws Exception
	 */
	public boolean send() throws Exception {
		String smtp = sendsetting.getSmtp();
		String account = sendsetting.getAccount();
		String passWord = sendsetting.getPassword();
		String mailServer = smtp;
		Properties prop = new Properties();
		prop.put(HOST, mailServer);
		prop.put(AUTH, "true");
		Session ss = Session.getInstance(prop);
		MimeMessage message = new MimeMessage(ss);
		try {
			message.setFrom(new InternetAddress(account));
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(
					user.getEmail()));
			Multipart mul = new MimeMultipart();
			BodyPart mbp = new MimeBodyPart();
			mbp.setContent(siteMessage.getContent(), "text/html ; charset=gbk");
			mul.addBodyPart(mbp);
			if (siteMessage.getMessageAttachment() != null) {
				mbp = new MimeBodyPart();
				String filename = siteMessage.getMessageAttachment().iterator()
						.next().getFilePath();
				FileDataSource fds = new FileDataSource(filename);
				DataHandler dh = new DataHandler(fds);
				mbp.setFileName(new String(filename.getBytes("GBK"),
						"ISO8859-1"));
				mbp.setDataHandler(dh);
				mul.addBodyPart(mbp);
			}
			message.setContent(mul);
			message.saveChanges();
			message.setSubject(siteMessage.getTitle());
			message.setSentDate(new Date());
			Transport ts = ss.getTransport("smtp");
			ts.connect(mailServer, account, passWord);
			ts.sendMessage(message, message.getAllRecipients());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	public TSiteMessage getSiteMessage() {
		return siteMessage;
	}

	public void setSiteMessage(TSiteMessage siteMessage) {
		this.siteMessage = siteMessage;
	}
}
